package service

import (
	"regexp"
	"strings"
	"unicode/utf8"
)

/*
	句子切分模块
	对于调用的翻译模型如果有长度限制，那么需要将段落切分成不超过最大长度的句子组，然后再进行翻译。
*/

// SentenceSplit 将输入的字符串按照换行符切分为多个句子返回一个数组
func SentenceSplit(input string) []string {
	// 按换行符分割
	lines := strings.Split(input, "\n")

	// 创建结果数组
	var sentences []string

	// 遍历所有行
	for _, line := range lines {
		// 移除首尾空白
		trimmed := strings.TrimSpace(line)

		// 跳过空行
		if trimmed != "" {
			sentences = append(sentences, trimmed)
		}
	}

	return sentences
}

// note: 将一个段落按照句号切分为多个句子，给出单个句子的最大长度，将句子进行组合，保证进行能返回的句子长度不超过最大长度，最终返回一个数组
// SplitParagraphBySentence 将段落按句号分割并控制长度
func SplitParagraphBySentence(paragraph string, maxLength int) []string {
	// 使用正则表达式匹配所有类型的句号
	re := regexp.MustCompile(`[。.．]`)

	// 按句号分割并保留句号
	var rawSentences []string
	lastIndex := 0

	// 查找所有句号位置
	matches := re.FindAllStringIndex(paragraph, -1)
	for _, match := range matches {
		sentence := strings.TrimSpace(paragraph[lastIndex:match[1]])
		if sentence != "" {
			rawSentences = append(rawSentences, sentence)
		}
		lastIndex = match[1]
	}

	// 处理最后剩余的内容
	if lastIndex < len(paragraph) {
		if final := strings.TrimSpace(paragraph[lastIndex:]); final != "" {
			rawSentences = append(rawSentences, final)
		}
	}

	// 组合句子，确保不超过最大长度
	var result []string
	var currentSentence string

	for _, sentence := range rawSentences {
		if currentSentence == "" {
			currentSentence = sentence
			continue
		}

		// 使用 RuneCountInString 计算实际字符数
		combinedLength := utf8.RuneCountInString(currentSentence + sentence)
		if combinedLength > maxLength {
			result = append(result, currentSentence)
			currentSentence = sentence
		} else {
			currentSentence += sentence
		}
	}

	// 添加最后一个句子
	if currentSentence != "" {
		result = append(result, currentSentence)
	}

	return result
}
